package com.azt.front.action.user;

import com.azt.api.dto.EnqProjListDto;
import com.azt.api.dto.EnqProjSearchDto;
import com.azt.api.enums.ApplyCompanyAuditStateEnum;
import com.azt.api.enums.LoginTypeEnum;
import com.azt.api.enums.OrderStateEnum;
import com.azt.api.enums.RoleTypeEnum;
import com.azt.api.exception.IncorrectCredentialsException;
import com.azt.api.exception.LockedAccountException;
import com.azt.api.exception.MailNotActiveException;
import com.azt.api.exception.UnknownAccountException;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.exception.BaseException;
import com.azt.front.action.BaseAction;
import com.azt.front.model.LoginCookie;
import com.azt.front.permission.RequireGuest;
import com.azt.front.permission.RequireUser;
import com.azt.front.service.UserFrontService;
import com.azt.front.utils.ContextUtil;
import com.azt.front.utils.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.FrontGlobals;
import com.azt.model.IforgotConstant;
import com.azt.model.VerifyCode;
import com.azt.model.page.Pagination;
import com.azt.model.page.TPagination;
import com.azt.utils.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserAction extends BaseAction {

    @Autowired
    private UserService userService;

    @Autowired
    private UserFrontService userFrontService;

    @Autowired
    private UserPermissionService userPermissionService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private FileService fs;
    
	@Autowired
	private OrderService orderService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private EnqEnquiryService enq;

    @Autowired
    private IntegralService integralService;

    /**
     * 载入登录页面
     * */
    @RequireGuest
    @RequestMapping("")
    public String index() {
        return "redirect:/user/login";
    }

    /**
     * 载入登录页面
     * */
    @RequireGuest
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
        //注入静态变量
        model.addAttribute("FrontGlobals", FreemarkerUtils.getStaticModel(FrontGlobals.class));
        return "user/login";
    }

    /**
     * 载入登录弹框
     * */
    @RequestMapping(value = "/loadLoginWin")
    public String loadLoginWin(Model model) {
        //注入静态变量
        model.addAttribute("FrontGlobals", FreemarkerUtils.getStaticModel(FrontGlobals.class));
        String callback = RequestUtils.getString("callback");
        model.addAttribute("callback",callback);
        User user = ContextUtil.getUser();
        model.addAttribute("user",user);
        return "user/loginWin";
    }
    /**
     * 载入绑定手机页面
     * Created by 张栋 on 2017/2/6 10:02
     */
    @RequestMapping(value = "/bindPhone")
    public String bindPhone(Model model) {
        String callback = RequestUtils.getString("callback");
        model.addAttribute("callback",callback);
        return "user/bindPhone";
    }

    /**
     * 验证手机
     * Created by 张栋 on 2017/2/6 10:34
     */
    @RequestMapping("/updatePhone")
    @ResponseBody
    public AjaxJson updatePhone(String code){
        AjaxJson j = new AjaxJson();
        User user = ContextUtil.getUser();
        VerifyCode verifyCode = (VerifyCode)request.getSession().getAttribute(Globals.SIGN_SAFECENTER_CODE);
        if(StringUtils.isNotBlank(code)) {
            if (verifyCode == null || !StringUtils.equalsIgnoreCase(verifyCode.getCode(), code.toString()) || verifyCode.getExpireTime().before(new Date())) {
                j.setSuccess(false);
                j.setMsg("验证码错误或超时");
                return j;
            }

            //成功验证  保存相应的数据
            String contactname = request.getParameter("contactname");
            if (StringUtils.isNotBlank(contactname)) {
                User userby = userService.getUserById(user.getId());
                if (PatternUtils.isMobile(contactname) && contactname.equals(verifyCode.getContact())) {
                    userby.setMobile(contactname);
                }
                userService.saveOrUpdate(userby);
                ContextUtil.setUser(userby);//刷新session

                j.setObj(userby.getMobile());
            } else {
                j.setSuccess(false);
                j.setMsg("手机号码不能为空");
            }
        }

        return j;
    }
    
    
    /**
     * 载入注册页面
     * */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Model model) {
        if(ContextUtil.isLogined()) {
            userFrontService.logout();
        }
        model.addAttribute("FrontGlobals", FreemarkerUtils.getStaticModel(FrontGlobals.class));
        model.addAttribute("type", "register");
        return "user/login";
    }

    /**
     * 用户登录操作
     * */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxJson login() {
        String username = getParaTrim("username");
        String password = request.getParameter("password");

        boolean rememberMe = CommonUtil.safeToBoolean(request.getParameter("rememberMe"), false);

        AjaxJson aj = AjaxJson.success();
        User user = null;
        try {
            user = userService.verifyLogin(username, password);
        } catch (UnknownAccountException e) {
            aj = AjaxJson.error("该账户名不存在");
        } catch (IncorrectCredentialsException e) {
            aj = AjaxJson.error("您输入的账户名和密码不匹配");
        } catch (LockedAccountException e) {
            aj = AjaxJson.error("账户被禁用");
        } catch (MailNotActiveException e) {
            //发送激活邮件
            User _user = (User)e.getData();
            if(_user != null) {
                userService.sendActiveMail(username, _user.getAuthString());
            }
            aj = AjaxJson.error("邮箱未激活");
            aj.setObj("/user/mailActive");

            //邮箱登录且未激活的时候还需要将用户信息存在session中，便于后面直接更换邮箱地址
            request.getSession().setAttribute(FrontGlobals.MAILNOTACTIVE_USER, _user);
        } catch (Exception e) {
            LOGGER.error("login error", e);
            aj = AjaxJson.error("认证失败");
        }

        if(aj.isSuccess() && user != null) {
            userFrontService.recordLoginSessionAndCookie(user, LoginTypeEnum.AUTH.getValue(), username, rememberMe, null);
        }
        return aj;
    }

    @ResponseBody
    @RequestMapping(value = "/sendActiveMail")
    public AjaxJson sendActiveMail() {
        User regUser = (User)request.getSession().getAttribute(FrontGlobals.MAILNOTACTIVE_USER);
        if(regUser != null && regUser.getMailActive() == 0) {
            userService.sendActiveMail(regUser.getEmail(), regUser.getAuthString());
            return AjaxJson.success();
        }
        return AjaxJson.error("发送失败");
    }

    /**
     * 邮箱激活页面修改邮箱地址并发送验证邮件
     * */
    @ResponseBody
    @RequestMapping(value = "/changeMail")
    public AjaxJson changeMail() {
        String mail = request.getParameter("mail");
        User mailNotActiveUser = (User)request.getSession().getAttribute(FrontGlobals.MAILNOTACTIVE_USER);
        try {
            if (mailNotActiveUser != null && mailNotActiveUser.getMailActive() == 0) {
                if (StringUtils.isBlank(mail)) {
                    return AjaxJson.error("请输入新邮箱");
                }
                mail = mail.trim();
                if (!PatternUtils.isEmail(mail)) {
                    return AjaxJson.error("邮箱格式有误");
                }
                if (mailNotActiveUser.getEmail().equals(mail)) {
                    return AjaxJson.error("邮箱地址未修改");
                }
                User _user = userService.getUserByEmail(mail);
                if (_user == null) {
                    //修改session中的mailNotActiveUser邮箱
                    User user = userService.getUserById(mailNotActiveUser.getId());
                    user.setAuthString(UUID.randomUUID().toString());
                    user.setEmail(mail);
                    user.setUpdatetime(new Date());
                    userService.saveOrUpdate(user);

                    userService.sendActiveMail(mail, user.getAuthString());
                    request.getSession().setAttribute(FrontGlobals.MAILNOTACTIVE_USER, user);
                    return AjaxJson.success();
                } else {
                    return AjaxJson.error("该邮箱已经注册");
                }
            }
        } catch (Exception e) {
            LOGGER.error("change email error", e);
        }
        return AjaxJson.error("操作失败");
    }

    @ResponseBody
    @RequestMapping(value = "/sendIforgotMail")
    public AjaxJson sendIforgotMail() {
        if(userFrontService.isValidIforgotRequest(request, null)) {
            User user = (User)request.getSession().getAttribute(IforgotConstant.USER_SESSION);
            userService.sendIforgotMail(user.getEmail(), user.getPwdString());
            return AjaxJson.success();
        }
        return AjaxJson.error("发送失败");
    }

    /**
     * 检测用户名是否可以用来注册
     * */
    @ResponseBody
    @RequestMapping(value = "/checkUserNameForRegister", method = RequestMethod.POST)
    public AjaxJson checkUserNameForRegister() {
        AjaxJson aj = AjaxJson.success();
        String username = request.getParameter("username");
        try {
            User user = userService.checkUserNameForRegister(username);
            if(user != null) {
                //只返回userid
                aj.setObj(user.getId());
            }
        } catch (BaseException e) {
            aj = AjaxJson.error(e.getErrorCode());
        }
        return aj;
    }

    /**
     * 找回密码页面验证：用户名+图片验证码
     * */
    @ResponseBody
    @RequestMapping(value = "/iforgotUserNameCheck", method = RequestMethod.POST)
    public Map iforgotUserNameCheck() {
        String field = request.getParameter("field");   //需要验证的字段
        String username = request.getParameter("username");     //用户名
        String code = request.getParameter("code");     //图片验证码

        Map<String, String> map = new HashMap<>();
        User user = null;
        if(StringUtils.contains(field, "username")) {
            if(StringUtils.isNotBlank(username)) {
                username = username.trim();
                if(PatternUtils.isMobile(username) || PatternUtils.isEmail(username)) {
                    user = userService.getUserByUserName(username);
                    if(user != null) {
                        map.put("user", "success");
                    } else {
                        map.put("user", "该" + (PatternUtils.isMobile(username) ? "手机号" : "邮箱") + "尚未注册");
                    }
                } else {
                    map.put("user", "请输入正确的手机号或邮箱");
                }
            } else {
                map.put("user", "请输入手机号或邮箱");
            }
        }
        if(StringUtils.contains(field, "code")) {
            if(StringUtils.isNotBlank(code)) {
                String forgotCode = CommonUtil.safeToString(request.getSession().getAttribute(IforgotConstant.CODE_SESSION));
                if(StringUtils.equalsIgnoreCase(code, forgotCode)) {
                    map.put("code", "success");
                } else {
                    map.put("code", "验证码错误，请重新输入");
                }
            } else {
                map.put("code", "请输入验证码");
            }
        }
        if(StringUtils.equals(map.get("code"), "success") && StringUtils.equals(map.get("user"), "success")) {
            //点击下一步，根据用户名类型返回下一步页面的url
            String url = PatternUtils.isMobile(username) ? "/user/iforgot2/mobile" : "/user/iforgot2/email";
            map.put("url", url);
            //找回密码step1 session记录
            request.getSession().setAttribute(IforgotConstant.STEP_SESSION, 2);     //当前位于第二步
            request.getSession().setAttribute(IforgotConstant.USER_SESSION, user);
            request.getSession().setAttribute(IforgotConstant.TYPE_SESSION, PatternUtils.isMobile(username) ? "mobile" : "email");
            request.getSession().removeAttribute(IforgotConstant.CODE_SESSION);

            if(PatternUtils.isMobile(username)) {
                //发送短信验证码
                userFrontService.sendIforgotSMS(request, response, username);
            } else {
                //生成找回密码激活码
                if(StringUtils.isBlank(user.getPwdString())) {
                    String pwdString = UUID.randomUUID().toString();
                    user.setPwdString(pwdString);
                    userService.saveOrUpdate(user);
                }
                //发送找回密码邮件
                userService.sendIforgotMail(username, user.getPwdString());
            }
        }
        return map;
    }

    /**
     * 找回密码发送短信验证码
     * */
    @ResponseBody
    @RequestMapping(value = "/sendIforgotSms", method = RequestMethod.POST)
    public AjaxJson sendIforgotSms() {
        String phone = request.getParameter("phone");
        if(StringUtils.isNotBlank(phone) && PatternUtils.isMobile(phone)) {
            userFrontService.sendIforgotSMS(request, response, phone);
            return AjaxJson.success();
        }
        return AjaxJson.error("发送失败");
    }

    /**
     * 发送注册短信验证码
     * */
    @ResponseBody
    @RequestMapping(value = "/sendRegisterSMS", method = RequestMethod.POST)
    public AjaxJson sendRegisterSMS() {
        String phone = getPara("phone");
        if(StringUtils.isNotBlank(phone) && PatternUtils.isMobile(phone)) {
            userFrontService.sendRegisterSMS(request, response, phone);
            return AjaxJson.success();
        }
        return AjaxJson.error("发送失败");
    }

    /**
     * 注册
     * */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public AjaxJson register() {
        String username = getParaTrim("username");     //帐号
        String password = getPara("password");     //密码
        String code = getPara("code");             //验证码
        boolean hasRead = CommonUtil.safeToBool(request.getParameter("hasRead"), false);       //是否阅读协议

        AjaxJson aj = AjaxJson.success();
        try {
            userService.checkUserNameForRegister(username);
        } catch (BaseException e) {
            return AjaxJson.error(e.getErrorCode());
        }
        if(StringUtils.isBlank(password)) {
            return AjaxJson.error("请输入密码");
        }
        if(password.contains(" ")) {
            return AjaxJson.error("密码不能包含“空格”，请重新输入");
        }
        if(password.length() < 6 || password.length() > 20) {
            return AjaxJson.error("密码为6-20个字符，可由英文、数字及符号组成");
        }
        if(StringUtils.isBlank(code)) {
            return AjaxJson.error("请输入验证码");
        }
        if(!hasRead) {
            return AjaxJson.error("需同意协议");
        }
        //判断验证码是否正确
        if(PatternUtils.isMobile(username)) {
            //手机注册，短信验证码
            VerifyCode vc = (VerifyCode)request.getSession().getAttribute(FrontGlobals.REGISTER_SMS_SESSION);
            if(vc == null) {
                return AjaxJson.error("请发送验证码");
            } else {
                if(!StringUtils.equals(code.trim(), vc.getCode()) || vc.getExpireTime().before(new Date())) {
                    return AjaxJson.error("验证码错误，请重新输入");
                }
            }
        } else if(PatternUtils.isEmail(username)) {
            //邮箱注册，图片验证码
            String regCode = CommonUtil.safeToString(request.getSession().getAttribute(FrontGlobals.REGISTER_CODE_SESSION));
            if(!StringUtils.equalsIgnoreCase(code, regCode)) {
                return AjaxJson.error("验证码错误，请重新输入");
            }
        }
        //开始注册
        User user = new User();
        if(PatternUtils.isMobile(username)) {
            user.setMobile(username);

            request.getSession().removeAttribute(FrontGlobals.REGISTER_SMS_SESSION);
        } else {
            //邮箱注册

            //生成邮箱激活码（u_user表中authString|当前时间|过期时间 经过AES加密而成，密钥为Globals.ACTIVEMAIL_KEY）
            String authString = UUID.randomUUID().toString();
            user.setEmail(username);
            user.setAuthString(authString);
            user.setMailActive(0);
            //发送激活邮件
            userService.sendActiveMail(username, authString);
            aj.setObj("/user/mailActive");

            request.getSession().removeAttribute(FrontGlobals.REGISTER_CODE_SESSION);
        }

        String salt = PasswordUtil.getRandomSalt(6);
        user.setSalt(salt);
        user.setPassword(PasswordUtil.encodePasswordForAZT(password, salt));
        user.setRegistertime(new Date());
        user.setState(1);
        user.setRemoved(0);
        user.setCreatetime(new Date());
        userService.saveOrUpdate(user);

        //新注册的用户角色为[注册用户]，将关联关系加到u_user_role表中
        //1. 获取注册用户的roleid
        Role role = userPermissionService.getRoleByRoleType(RoleTypeEnum.REGISTER.getValue()).get(0);
        //2. 将该用户赋为注册用户
        userPermissionService.insertUserRole(user.getId(), role.getId());

        if(PatternUtils.isEmail(username)) {
            //邮箱注册的时候还需要将用户信息存在session中，便于直接更换邮箱地址
            request.getSession().setAttribute(FrontGlobals.MAILNOTACTIVE_USER, user);
        } else {
            //手机注册的时候为其注入必要的session和cookie
            userFrontService.recordLoginSessionAndCookie(user, LoginTypeEnum.AUTH.getValue(), username, false, null);
        }

        return aj;
    }

    /**
     * 邮箱激活<br>
     * 参数：username、code（u_user表中authString|当前时间|过期时间 经过AES加密而成，密钥为Globals.ACTIVEMAIL_KEY）
     * */
    @RequestMapping(value = "/activeMail")
    public String activeMail() {
        String username = request.getParameter("username");
        String code = request.getParameter("code");
        if (StringUtils.isNoneBlank(username, code) && PatternUtils.isEmail(username)) {
            User user = userService.getUserByEmail(username);
            if(user != null) {
                //校验code
                String rawCode = AESUtil.decrypt(code, FrontGlobals.ACTIVEMAIL_KEY);
                if(StringUtils.isNotBlank(rawCode)) {
                    String[] array = rawCode.split("\\|");
                    if(array.length == 4) {
                        String authString = array[0];
                        String email = array[1];
                        String createString = array[2];
                        String expireString = array[3];
                        if(StringUtils.isNoneBlank(authString, email, createString, expireString)) {
                            //判断该链接是否过期
                            Date expireDate = CommonUtil.safeToDate(expireString, "yyyyMMddHHmmss");
                            if(expireDate != null && StringUtils.equals(authString, user.getAuthString()) && username.equals(email)) {
                                if(expireDate.after(new Date())) {
                                    if(user.getMailActive() == 0) {
                                        //验证通过，激活邮箱
                                        user.setMailActive(1);
                                        userService.saveOrUpdate(user);
                                        userFrontService.recordLoginSessionAndCookie(user, LoginTypeEnum.AUTH.getValue(), username, false, null);
                                        return "redirect:/user/regSuccess";
                                    } else {
                                        //用户已激活
                                        return "redirect:/user/activeMsg/actived";
                                    }
                                } else {
                                    //链接失效
                                    return "redirect:/user/activeMsg/expired";
                                }
                            }
                        }
                    }
                }
            }
        }
        return "redirect:/user/activeMsg/error";
    }

    /**
     * 邮箱找回密码<br>
     * 参数：username、code（u_user表中authString|当前时间|过期时间|iforgot 经过AES加密而成，密钥为IforgotConstant.EMAIL_KEY）
     * */
    @RequestMapping(value = "/iforgotEmail")
    public String iforgotEmail() {
        String username = request.getParameter("username");
        String code = request.getParameter("code");
        LOGGER.info(code);
        if (StringUtils.isNoneBlank(username, code) && PatternUtils.isEmail(username)) {
            User user = userService.getUserByEmail(username);
            if(user != null) {
                //校验code
                String rawCode = AESUtil.decrypt(code, IforgotConstant.EMAIL_KEY);
                if(StringUtils.isNotBlank(rawCode)) {
                    String[] array = rawCode.split("\\|");
                    if(array.length == 5) {
                        String pwdString = array[0];
                        String email = array[1];
                        String createString = array[2];
                        String expireString = array[3];
                        String type = array[4];
                        if(StringUtils.isNoneBlank(pwdString, createString, expireString) && StringUtils.equals(type, "iforgot") && username.equals(email)) {
                            //判断该链接是否过期
                            Date expireDate = CommonUtil.safeToDate(expireString, "yyyyMMddHHmmss");
                            if(expireDate != null && StringUtils.equals(pwdString, user.getPwdString())) {
                                if(expireDate.after(new Date())) {
                                    //验证通过，跳转到找回密码第三步
                                    request.getSession().setAttribute(IforgotConstant.STEP_SESSION, 3);
                                    request.getSession().setAttribute(IforgotConstant.USER_SESSION, user);
                                    request.getSession().setAttribute(IforgotConstant.TYPE_SESSION, "email");
                                    return "redirect:/user/iforgot3";
                                } else {
                                    //链接失效
                                    return "redirect:/user/activeMsg/expired";
                                }
                            }
                        }
                    }
                }

            }
        }
        return "redirect:/user/activeMsg/error";
    }

    /**
     * 找回密码：短信验证码校验
     * */
    @ResponseBody
    @RequestMapping(value = "/iforgotSMSCheck", method = RequestMethod.POST)
    public AjaxJson iforgotSMSCheck() {
        String code = request.getParameter("code");
        boolean next = CommonUtil.safeToBool(request.getParameter("next"), false);
        if(StringUtils.isNotBlank(code)) {
            VerifyCode vc = (VerifyCode) request.getSession().getAttribute(IforgotConstant.SMS_SESSION);
            if(vc != null && vc.getExpireTime().after(new Date()) && StringUtils.equals(code, vc.getCode())) {
                if(next) {
                    //进入到第三步
                    request.getSession().setAttribute(IforgotConstant.STEP_SESSION, 3);
                    request.getSession().removeAttribute(IforgotConstant.SMS_SESSION);
                }
                return AjaxJson.success();
            } else {
                return AjaxJson.error("验证码错误，请重新输入");
            }
        } else {
            return AjaxJson.error("请输入验证码");
        }
    }

    /**
     * 找回密码第三步：校验密码
     * */
    @ResponseBody
    @RequestMapping(value = "/iforgotPwdCheck", method = RequestMethod.POST)
    public Map iforgotPwdCheck() {
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");
        String field = request.getParameter("field");

        Map<String, String> map = new HashMap<>();
        if(StringUtils.contains(field, "password1")) {
            if(StringUtils.isBlank(password1)) {
                map.put("password1", "请输入密码");
            } else if(password1.contains(" ")) {
                map.put("password1", "密码不能包含‘空格’");
            } else if(password1.length() < 6 || password1.length() > 20) {
                map.put("password1", "密码为6-20个字符，可由英文、数字符号组成");
            } else {
                map.put("password1", "success");
            }
        }
        if(StringUtils.contains(field, "password2")) {
            if(StringUtils.isBlank(password2)) {
                map.put("password2", "请再次输入密码");
            } else if(!StringUtils.equals(password1, password2)) {
                map.put("password2", "两次密码输入不一致");
            } else {
                map.put("password2", "success");
            }
        }

        if(StringUtils.equals(map.get("password1"), "success") && StringUtils.equals(map.get("password2"), "success")) {
            //重设密码
            if(userFrontService.isValidIforgotRequest(request, 3)) {
                User user = (User)request.getSession().getAttribute(IforgotConstant.USER_SESSION);
                userService.resetPassword(user.getId(), password1);
                request.getSession().removeAttribute(IforgotConstant.USER_SESSION);
                request.getSession().removeAttribute(IforgotConstant.STEP_SESSION);
                request.getSession().removeAttribute(IforgotConstant.TYPE_SESSION);

                //如果是通过邮箱找回的，则还需要重新设置u_user表中的pwdString，防止通过这个链接无限改密码
                String type = CommonUtil.safeToString(request.getSession().getAttribute(IforgotConstant.TYPE_SESSION));
                if("email".equals(type)) {
                    User _user = userService.getUserById(user.getId());
                    if(_user != null) {
                        String pwdString = UUID.randomUUID().toString();
                        _user.setPwdString(pwdString);
                        userService.saveOrUpdate(_user);
                    }
                }
            }
        }
        return map;
    }

    @RequestMapping(value = "/iforgotSuccess", method = RequestMethod.GET)
    public String iforgotSuccess() {
        return "user/iforgotSuccess";
    }

    /**
     * 载入注册成功页面
     * */
    @RequestMapping(value = "/regSuccess", method = RequestMethod.GET)
    public String regSuccess() {
        return "user/regSucc";
    }

    @RequestMapping(value = "/mailActive", method = RequestMethod.GET)
    public String mailActive() {
        //request.setAttribute("mail", request.getParameter("mail"));
        User mailNotActiveUser = (User) request.getSession().getAttribute(FrontGlobals.MAILNOTACTIVE_USER);
        if(mailNotActiveUser == null) {
            return "redirect:/";
        }
        return "user/mailActive";
    }

    @RequestMapping(value = "/activeMsg/{type}", method = RequestMethod.GET)
    public String activeMsg(@PathVariable("type") String type, Model model) {
        boolean success = false;
        String title = "激活失败";
        String content = "此链接无效";
        if(StringUtils.isNotBlank(type)) {
            switch (type) {
                case "success" :
                    //激活成功
                    success = true;
                    title = "激活成功";
                    content = "您已完成激活";
                    break;
                case "expired" :
                    //链接过期
                    title = "激活失败";
                    content = "此链接已失效";
                    break;
                case "actived" :
                    //用户已激活
                    title = "激活失败";
                    content = "对不起，您已完成激活，此链接已失效";
                    break;
                default:
                    //链接无效
            }
        }
        model.addAttribute("success", success);
        model.addAttribute("title", title);
        model.addAttribute("content", content);
        return "user/activeMsg";
    }

    /**
     * 载入忘记密码页面
     * */
    @RequestMapping(value = "/iforgot", method = RequestMethod.GET)
    public String iforgot() {
        return "user/iforgot";
    }

    /**
     * 载入忘记密码第二步
     * */
    @RequestMapping(value = "/iforgot2/{type}", method = RequestMethod.GET)
    public String iforgot2(@PathVariable("type") String type, Model model) {
        User user = (User)request.getSession().getAttribute(IforgotConstant.USER_SESSION);
        String iforgotType = CommonUtil.safeToString(request.getSession().getAttribute(IforgotConstant.TYPE_SESSION));
        if(user != null && StringUtils.isNotBlank(iforgotType) && ("email".equals(iforgotType) || "mobile".equals(iforgotType)) && iforgotType.equals(type)) {
            model.addAttribute("user", user);

            if(StringUtils.equals(type, "mobile")) {
                return "user/iforgotMobile2";
            } else if(StringUtils.equals(type, "email")) {
                return "user/iforgotMail2";
            }
        }
        //非法操作，跳转到第一步
        return "redirect:/user/iforgot";
    }

    /**
     * 载入找回密码第三步<br>
     * 校验session中找回密码的用户以及当前步数
     * */
    @RequestMapping(value = "/iforgot3", method = RequestMethod.GET)
    public String iforgot3() {
        if(userFrontService.isValidIforgotRequest(request, 3)) {
            User user = (User)request.getSession().getAttribute(IforgotConstant.USER_SESSION);
            String type = CommonUtil.safeToString(request.getSession().getAttribute(IforgotConstant.TYPE_SESSION));
            request.setAttribute("username", "email".equals(type) ? user.getEmail() : user.getMobile());
            return "user/iforgot3";
        } else {
            return "redirect:/user/iforgot";
        }
    }

    /**
     * 系统登出
     * */
    @ResponseBody
    @RequestMapping(value = "/logout")
    public AjaxJson logout() {
        userFrontService.logout();
        return AjaxJson.success();
    }

    /*
    *文件系统入口
    * */
    @RequestMapping(value = "/fileManager")
    public String fileManager(Model model , String initType , Boolean multiple , Integer pageNo ){
    	model.addAttribute("initType", initType);
    	model.addAttribute("multiple", multiple);
    	//model.addAttribute("index", index);

        Pagination p = new Pagination();
        //不管登不登陆都可以用
        if(ContextUtil.getUser() != null){
            Map<String , Object> params = new HashMap<String , Object>();
            params.put("userId" , ContextUtil.getUserId());
            params.put("isImage" , "image".equals(initType) ? 1 : 0);
            //List<File> myfiles = fs.getMyFiles(ContextUtil.getUserId() , "image".equals(initType) ? 1 : 0);
            p = fs.getMyfilesBySearch(pageNo == null ? 1 : pageNo , 12, params);
        }else{//用户未登陆就从session里面取临时文件
            Object tfs = ContextUtil.getSession().getAttribute(Globals.TEMP_FILE);
            if(tfs != null) {
                List ttf = new ArrayList();
                Integer ifimage = (initType.equals("image") ? 1 : 0);
                for(Object f : (List)tfs){
                    File fi = (File)f;
                    if(fi.getIsImage() == ifimage){
                        ttf.add(fi);
                    }
                }
                p.setList(ttf);
            }
        }

        model.addAttribute("pagination" , p);
    	return "common/fileManager";
    }

    @RequestMapping(value = "/fileManagerNew")
    public String fileManagerNew(Model model , String initType , Boolean multiple , Integer pageNo ,Integer chioseId){
    	model.addAttribute("initType", initType);
    	model.addAttribute("multiple", multiple);
    	model.addAttribute("chioseId", chioseId);
    	//model.addAttribute("index", index);

        Pagination p = new Pagination();
        //不管登不登陆都可以用
        if(ContextUtil.getUser() != null){
            Map<String , Object> params = new HashMap<String , Object>();
            params.put("userId" , ContextUtil.getUserId());
            params.put("isImage" , "image".equals(initType) ? 1 : 0);
            //List<File> myfiles = fs.getMyFiles(ContextUtil.getUserId() , "image".equals(initType) ? 1 : 0);
            p = fs.getMyfilesBySearch(pageNo == null ? 1 : pageNo , 14, params);
        }else{//用户未登陆就从session里面取临时文件
            Object tfs = ContextUtil.getSession().getAttribute(Globals.TEMP_FILE);
            if(tfs != null) {
                List ttf = new ArrayList();
                Integer ifimage = (initType.equals("image") ? 1 : 0);
                for(Object f : (List)tfs){
                    File fi = (File)f;
                    if(fi.getIsImage() == ifimage){
                        ttf.add(fi);
                    }
                }
                p.setList(ttf);
            }
        }

        model.addAttribute("pagination" , p);
    	return "common/fileManagerNew";
    }

    /*
    * 文件系统保存文件方法
    * */
    @RequestMapping(value = "/saveFile")
    @ResponseBody
    public void saveFile(HttpServletResponse response , File file ){
        if(file.getUrl() != null){
            file.setCreatetime(new Date());
            if(ContextUtil.getUser() != null){
                PrintWriter out = null;
                try {
                    file.setUserId(ContextUtil.getUserId());
                    fs.saveOrUpdateFile(file);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html; charset=utf-8");
                    out = response.getWriter();
                    out.append(file.getId().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    out.close();
                }
            }else{//用户未登陆则保存到session中作为临时文件
                Object tf = ContextUtil.getSession().getAttribute(Globals.TEMP_FILE);
                List<File> tfs = new ArrayList<File>();
                if(tf != null){
                    tfs = (List<File>)tf;
                }
                tfs.add(file);
                ContextUtil.getSession().setAttribute(Globals.TEMP_FILE , tfs);
            }
        }
    }

    @RequestMapping(value = "/delFile")
    @ResponseBody
    public void delFile(String fids){
        if(!com.alibaba.druid.util.StringUtils.isEmpty(fids)){
            fs.delFile(fids);
        }
    }

    /**
     * 载入搜索企业页面
     * */
    @RequireUser
    @RequestMapping(value = "/companySearch")
    public String companySearch(Model model) {
        UserApplyCompany uac = userService.getAuditingApplyCompany(ContextUtil.getUserId());
        if(uac != null) {
            model.addAttribute("uac", uac);
        }
        return "company/companySearch";
    }

    /**
     * 载入申请加入企业页面
     * */
    @RequireUser
    @RequestMapping(value = "/companyApply/{id}", method = RequestMethod.GET)
    public String companyApply(@PathVariable Integer id, Model model) {
        String redirectBack = "redirect:/user/companySearch";
        if(id == null) {
            return redirectBack;
        }
        Company company = companyService.getCompanyById(id);
        if(company == null) {
            return redirectBack;
        }

        //获取该公司下的角色信息
        List<Role> roleList = userPermissionService.findRoleNotAdmin(id);

        model.addAttribute("company", company);
        model.addAttribute("roleList", roleList);
        return "company/companyApply";
    }

    /**
     * 根据部门查询所属角色信息
     */
    @ResponseBody
    @RequestMapping(value = "/findRoleByDept", method = RequestMethod.POST)
    public AjaxJson findRoleByDept() {
        Integer deptId = CommonUtil.safeToInteger(request.getParameter("deptId"));

        AjaxJson aj = AjaxJson.success();
        if(deptId != null) {
           // List<Role> roleList = userPermissionService.findRoleByDept(deptId, 0, null);
       /*     if(roleList != null && roleList.size() > 0) {
                aj.setObj(roleList);
                return aj;
            }*/
        }
        return AjaxJson.error("no");
    }

    @RequireUser
    @ResponseBody
    @RequestMapping(value = "/saveApplyCompany", method = RequestMethod.POST)
    public AjaxJson saveApplyCompany() {
        Integer companyId = CommonUtil.safeToInteger(request.getParameter("companyId"));
        Integer roleId = CommonUtil.safeToInteger(request.getParameter("roleId"));
        String realName = request.getParameter("realName");
        String mobile = request.getParameter("mobile");
        String applyReason = request.getParameter("applyReason");
        User user = ContextUtil.getUser();

        if(user.getCompanyId() != null) {
            return AjaxJson.error("您已加入一个企业，无法再次申请");
        }
        if(user != null && user.getCompanyId() == null && companyId != null && StringUtils.isNoneBlank(realName, mobile, applyReason)) {
            if(userService.getAuditingApplyCompany(user.getId()) != null) {
                return AjaxJson.error("您已有一个审核中的申请，无法再次申请");
            }

            UserApplyCompany uac = new UserApplyCompany();
            uac.setUserId(user.getId());
            uac.setCompanyId(companyId);
            uac.setRoleId(roleId);
            uac.setRealName(realName);
            uac.setMobile(mobile);
            uac.setApplyReason(applyReason);
            uac.setAuditState(ApplyCompanyAuditStateEnum.INIT.getValue());  //待审核
            userService.insertUserApplyCompany(uac);
            return AjaxJson.success();
        }

        return AjaxJson.error("系统繁忙，请稍后再试");
    }

    /**
     * 搜索已经审核通过的企业
     * */
    @ResponseBody
    @RequestMapping(value = "/searchCompany")
    public Map searchCompany() {
        String keyword = getParaTrim("keyword");
        Integer pageNo = getParaToInt("page", 1);

        Map data = new HashMap();
        if(StringUtils.isNotBlank(keyword)) {
            Page page = PageHelper.startPage(pageNo, 10);
            List<Company> list = companyService.searchCompanyByKeyword(keyword);
            List<Map> result = new ArrayList<>();
            for(Company company : list) {
                Map m = new HashMap();
                m.put("companyName", company.getCompanyName());
                m.put("companyId", company.getId());
                result.add(m);
            }
            data.put("data", result);
            data.put("hasNext", page.getPages() > pageNo);
        }
        return data;
    }
    


	/**
     * 角色切换
     * */
    
	@RequestMapping(value = "/switch", produces = "application/json;charset=UTF-8")
    @ResponseBody
	public AjaxJson switchRole() {
        Integer roleType = ContextUtil.getCurrentRoleType();
        if(roleType != null && (roleType.equals(RoleTypeEnum.PURCHASER.getValue()) || roleType.equals(RoleTypeEnum.PROVIDER.getValue()))) {
            Integer switchTo = roleType.equals(RoleTypeEnum.PURCHASER.getValue()) ? RoleTypeEnum.PROVIDER.getValue() : RoleTypeEnum.PURCHASER.getValue();

            List<Role> roles = ContextUtil.getRoles();
            for(Role role : roles) {
                if(role != null && role.getRoleType().equals(switchTo)) {
                    ContextUtil.setCurrentRole(role);

                    //变更cookie中的currentRoleId
                    LoginCookie cookie = ContextUtil.getLoginCookie();
                    if(cookie != null) {
                        LoginCookie newCookie = new LoginCookie(cookie.getUserId(), cookie.getUsername(), role.getId(),
                                cookie.getSalt(), cookie.getLoginTime(), cookie.getExpireTime());
                        ContextUtil.setLoginCookie(newCookie);
                    }
                    return AjaxJson.success();
                }
            }
        }
        return AjaxJson.error("操作异常");
    }
	
	/** 
	 * @Title: userCenter 
	 * @Description: 商户中心
	 * @param roleType
	 * @return: String
	 * @author: 查恒 2016年11月18日 下午4:27:09 
	 */
	@RequireUser
	@RequestMapping("/userCenter")
	public String  userCenter(Model model){
        Role currentRole = ContextUtil.getCurrentRole();
        User currentuser = ContextUtil.getUser();
        Company company = ContextUtil.getCompany();

		model.addAttribute("company", company);
		model.addAttribute("currentUser", currentuser);
		model.addAttribute("currentRole", currentRole);

		if(company!=null) {
			Company topCompany = companyService.getTopParentCompany(company.getId());
			model.addAttribute("topCompany", topCompany);
			//用户的基本数据
			double transactions = orderService.getTransactions(company, currentRole.getRoleType());
			Map userInfo=userService.getUserInfo(company,currentRole,currentuser);
			model.addAttribute("companySign", userInfo.get("companySign"));
			model.addAttribute("userAccount", userInfo.get("userAccount"));
			model.addAttribute("coinCount", coinService.getCoinByCompanyId(company.getId()));

            int unPayOrderCount = orderService.getMyQuoteOrderCount(currentRole.getRoleType(), ContextUtil.isAdmin(), company, currentuser, OrderStateEnum.UNPAY.getValue(), false);  //待付款订单数量
            int payedOrderCount = orderService.getMyQuoteOrderCount(currentRole.getRoleType(), ContextUtil.isAdmin(), company, currentuser, OrderStateEnum.PAYED.getValue(), false);  //已支付订单数量
            int shipedOrderCount = orderService.getMyQuoteOrderCount(currentRole.getRoleType(), ContextUtil.isAdmin(), company, currentuser, OrderStateEnum.SHIPED.getValue(), false);  //已发货订单数量
            model.addAttribute("unPayOrderCount", unPayOrderCount);
            model.addAttribute("payedOrderCount", payedOrderCount);
            model.addAttribute("shipedOrderCount", shipedOrderCount);
            model.addAttribute("transactions", transactions);

			if(currentRole.getRoleType()==RoleTypeEnum.PURCHASER.getValue()){//采购商入口
                //预算询价收到的报价
                Integer designcount = enq.getQuoteCountByType(currentuser.getId(),1);
                model.addAttribute("designcount",designcount);
                //采购询价收到的报价
                Integer purchasecount = enq.getQuoteCountByType(currentuser.getId(),2);
                model.addAttribute("purchasecount",purchasecount);

                //我的项目
                EnqProjSearchDto dto = new EnqProjSearchDto();
                dto.setUserId(currentuser.getId());
                dto.setCustomerId(company.getId());
                TPagination<EnqProjListDto> myProject = enq.getMyProject(null, 4, dto);
                List<EnqProjListDto> list = myProject.getList();
                model.addAttribute("projects",list);

                //判断权限,判断有没有菜单
                //验证权限,有没有发布的权限
                boolean hasDesignPermission = userPermissionService.hasThisPerm(ContextUtil.getCurrentRole().getId(), new String[]{"DesignEnquiry"}, 2);
                boolean hasPurchasePermission = userPermissionService.hasThisPerm(ContextUtil.getCurrentRole().getId(), new String[]{"PurchaseEnquiry"}, 2);

                model.addAttribute("hasDesignPermission",hasDesignPermission);
                model.addAttribute("hasPurchasePermission",hasPurchasePermission);

				return "user/userPurchase";
			}else if(currentRole.getRoleType()==RoleTypeEnum.PROVIDER.getValue()){//供应商入口

				model.addAttribute("pushEnquiryCount", enq.getPushEnquiryCount(company.getId()));
				model.addAttribute("myDesQutCount", enq.getMyQuoteCount(currentuser.getId() , company.getId() , EnqEnquiry.DESIGN_ENQUIRY));
				model.addAttribute("myPurQutCount", enq.getMyQuoteCount(currentuser.getId() , company.getId() , EnqEnquiry.PUR_ENQUIRY));
				model.addAttribute("quoteList", enq.getCenterQuoteList(currentuser.getId() , company.getId()));

                Boolean centralizeboolean = companyService.getCentralizePurchaseByCompanyId(company.getId());//查询集采供应商
				model.addAttribute("centralizeboolean", centralizeboolean==true?"1":"0");
				return "user/userProvider";
			} else {
                return "redirect:/company/info";
            }
		}else{//注册用户入口
			return "redirect:/user/companySearch";
		}
		
	}
}
